package com.changpay.zywy.wight;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import com.changpay.zywy.R;


public class WheelCircleView extends View {
    private final String TAG = getClass().getSimpleName();

    private int mWidth = dp2Px(48), mHeight = dp2Px(48), mCenterX, mCenterY;

    // 默认刻度画笔、指针画笔、文字画笔；
    private Paint mDefaultPaint;
    private Paint mTextPaint;

    private CircleBarAnim circleBarAnim;

    private float mRadius, mPointRadius,
            mDefaultScaleLength, mDefaultScaleWidth;

    private int mClockColor, mColorDefaultScale, mTextColor;
    private float sweepTime = 0;
    private int times;
    private int precentOne = 18, precentTwo = 18;
    private String PrecentText = "0%";
    private float textSize = 0;
    private boolean hasText;


    public WheelCircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        // 获取自定义属性值
        getAttrs(context, attrs);
        // 初始化
        init();
    }

    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ClockView);
        mClockColor = a.getColor(R.styleable.ClockView_OneCircleColor, Color.BLACK);
        mColorDefaultScale = a.getColor(R.styleable.ClockView_TwoCircleColor, mClockColor);
        mTextColor = a.getColor(R.styleable.ClockView_textColor, mClockColor);
        hasText = a.getBoolean(R.styleable.ClockView_hasText, false);
        times = a.getInt(R.styleable.ClockView_animationTime, 3000);
        textSize = a.getDimension(R.styleable.ClockView_textSize, dp2Px(15));
        a.recycle();//不要忘记回收！
    }

    private void init() {
        circleBarAnim = new CircleBarAnim();
        circleBarAnim.setDuration(times);


        mDefaultPaint = new Paint();
        mDefaultPaint.setAntiAlias(true);
        mDefaultPaint.setStyle(Paint.Style.STROKE);
        mDefaultPaint.setStrokeCap(Paint.Cap.ROUND);

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(mTextColor);
        mTextPaint.setStyle(Paint.Style.STROKE);
        mTextPaint.setTextSize(textSize);

    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        mCenterX = w / 2;
        mCenterY = h / 2;
        mRadius = (float) (w / 2 * 0.8);

        initClockPointerLength();
    }

    /**
     * 根据控件的大小，初始化时钟刻度的长度和宽度、指针的长度和宽度、时钟中心点的半径
     */
    private void initClockPointerLength() {


        mDefaultScaleLength = mRadius / 3 + 5;
        mDefaultScaleWidth = mDefaultScaleLength / 5;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getMeasureSize(true, widthMeasureSpec);
        int height = getMeasureSize(false, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    /**
     * 获取View尺寸
     * 基本上算是标准写法
     *
     * @param isWidth 是否是width，不是的话，是height
     */
    private int getMeasureSize(boolean isWidth, int measureSpec) {

        int result = 0;

        int specSize = MeasureSpec.getSize(measureSpec);
        int specMode = MeasureSpec.getMode(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                if (isWidth) {
                    result = getSuggestedMinimumWidth();
                } else {
                    result = getSuggestedMinimumHeight();
                }
                break;
            case MeasureSpec.AT_MOST:   // at_most中的specsize为子view可以拿到的最大值
                if (isWidth)
                    result = Math.min(specSize, mWidth);
                else
                    result = Math.min(specSize, mHeight);
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 坐标原点移动到View 中心
        canvas.translate(mCenterX, mCenterY);
        drawCircle(canvas);
    }

    /**
     * 绘制时钟的圆形和刻度
     */
    private void drawCircle(Canvas canvas) {
        if (hasText) {
            float textWidth = mTextPaint.measureText(PrecentText);
            float Textx = 0 - textWidth / 2;
            Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
            float dy = (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
            float Texty = 0 + dy;
            canvas.drawText(PrecentText, Textx, Texty, mTextPaint);
        }
        mDefaultPaint.setStrokeWidth(mDefaultScaleWidth);
        for (int i = 0; i < sweepTime; i++) {
            if (i < precentOne) {
                mDefaultPaint.setColor(mClockColor);
                canvas.drawLine(0, -mRadius, 0, -mRadius + mDefaultScaleLength, mDefaultPaint);
                canvas.rotate(10);
            } else {
                mDefaultPaint.setColor(mColorDefaultScale);
                canvas.drawLine(0, -mRadius, 0, -mRadius + mDefaultScaleLength, mDefaultPaint);
                canvas.rotate(10);
            }
        }

    }


    private int dp2Px(int dp) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }


    public class CircleBarAnim extends Animation {
        public CircleBarAnim() {
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            sweepTime = interpolatedTime * 36;
            postInvalidate();
        }
    }

    public void starAnim() {
        sweepTime = 0;
        this.startAnimation(circleBarAnim);
    }

    public void setData(int act, int unAct) {
        if (act + unAct == 0) {
            precentOne = 36;
            precentTwo = 0;
            PrecentText = "0%";
        } else if (act == 0)  // 当激活数为0的时候
        {
            precentOne = 36;
            precentTwo = 0;
            PrecentText = "0%";
        } else {
            float precent = (float) act / (act + unAct) * 100;
            String filesize = String.valueOf((int) precent);
            PrecentText = filesize + "%";
            float tempPrecent = precent * 36 / 100;
            if (tempPrecent < 1) {
                precentTwo = 1;

            } else {
                precentTwo = (int) tempPrecent;
            }
            precentOne = 36 - precentTwo;
        }
        starAnim();
    }

        public void setDataPer(int act, int total) {
        if (total == 0 || act == 0)  // 当激活数为0的时候
        {
            precentOne = 0;
            precentTwo = 36;
            PrecentText = "0%";
        } else {
            float precent = (float) act / total * 100;
            String filesize = String.valueOf((int) precent);
            PrecentText = filesize + "%";
            float tempPrecent = precent * 36 / 100;
            if (tempPrecent < 1) {
                precentOne = 1;

            } else {
                precentOne = (int) tempPrecent;
            }
            precentTwo = 36 - precentOne;
        }
        starAnim();
    }

    public void setDataDan(int act, int unAct) {
        if (act + unAct == 0) {
            precentOne = 0;
            precentTwo = 36;
            PrecentText = "0%";
        } else if (act == 0)  // 当激活数为0的时候
        {
            precentOne = 0;
            precentTwo = 36;
            PrecentText = "0%";
        } else {
            float precent = (float) act / (act + unAct) * 100;
            String filesize = String.valueOf((int) precent);
            PrecentText = filesize + "%";
            float tempPrecent = precent * 36 / 100;
            if (tempPrecent < 1) {
                precentOne = 1;

            } else {
                precentOne = (int) tempPrecent;
            }
            precentTwo = 36 - precentOne;
        }
        starAnim();
    }

    public void setOneCircleColor(String color)
    {
        mClockColor = Color.parseColor(color);
        mTextColor = Color.parseColor(color);
        mTextPaint.setColor(mTextColor);
    }
}
